package com.data.app.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Zyl
 * @Date 2021/4/13 10:37
 * @Version 1.0
 * @Describe:
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryPostgresql",
        transactionManagerRef = "transactionManagerPostgresql",
        basePackages = {"com.data.app.dao.pg"}
)
public class PostGresqlConfig {
    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    @Qualifier("postgresqlDataSource")
    private DataSource postgresqlDataSource;

    @Autowired
    private HibernateProperties hibernateProperties;

    @Value("${spring.jpa.hibernate.postgresql-dialect}")
    private String postgresqlDialect;

    /**
     *
     * @param builder
     * @return
     */
    @Bean(name = "entityManagerFactoryPostgresql")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPostgresql(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(postgresqlDataSource)
                .properties(jpaProperties.getProperties())
                .properties(getVendorProperties())
                .packages("com.data.app.pojo.pg")
                .persistenceUnit("postgresqlPersistenceUnit")
                .build();
    }

    private Map<String, ?> getVendorProperties() {
        Map<String,String> map = new HashMap<>();
        map.put("hibernate.dialect",postgresqlDialect);
        map.put("hibernate.show-sql","true");
        jpaProperties.setProperties(map);
        return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
    }

    /**
     * 配置事物管理器
     *
     * @param builder
     * @return
     */
    @Bean(name = "transactionManagerPostgresql")
    PlatformTransactionManager transactionManagerPostgresql(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPostgresql(builder).getObject());
    }
}
